package cn.amossun.starter.web.data.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.amossun.starter.common.constant.Constant;
import cn.amossun.starter.mybatis.data.security.runner.OrmConfigCacheRunner;
import cn.amossun.starter.redis.cache.connection.MultiRedisLettuceConnectionFactory;
import cn.amossun.starter.redis.cache.exception.RedisCacheConfigException;
import cn.amossun.starter.redis.cache.exception.RedisRelatedException;
import cn.amossun.starter.redis.cache.properties.MultiRedisProperties;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/03/08 19:00
 **/
public interface IServiceRedisConfig {

	String ORM_CACHE_KEY_VERSION = OrmConfigCacheRunner.ORM_CACHE_KEY + Constant.COLON + "version";

	default void assertService(String serviceName) throws RedisRelatedException, RedisCacheConfigException {
		if(StrUtil.isEmpty(serviceName)) {
			throw new RedisCacheConfigException("请选择应用服务.");
		}
		//切换对应服务redis数据源
		SpringUtil.getBean(MultiRedisLettuceConnectionFactory.class).setCurrentRedis(serviceName);
	}

	default String getSecurityConfigKey(String serviceName) {
		String prefix = appendPrefix(serviceName);
		if(StrUtil.isEmpty(prefix)) {
			return OrmConfigCacheRunner.ORM_CACHE_KEY;
		}
		return new StringBuilder(prefix.trim()).append(Constant.COLON).append(OrmConfigCacheRunner.ORM_CACHE_KEY).toString();
	}

	default String getSecurityVersionKey(String serviceName) {
		String prefix = appendPrefix(serviceName);
		if(StrUtil.isEmpty(prefix)) {
			return ORM_CACHE_KEY_VERSION;
		}
		return new StringBuilder(prefix.trim()).append(Constant.COLON).append(ORM_CACHE_KEY_VERSION).toString();
	}

	default String appendPrefix(String serviceName) {
		MultiRedisProperties multiRedisProperties = SpringUtil.getBean(MultiRedisProperties.class);
		if(ObjectUtil.isNull(multiRedisProperties) ||
				CollectionUtil.isEmpty(multiRedisProperties.getDynamic())) {
			return StrUtil.EMPTY;
		}
		MultiRedisProperties.DynamicRedisProperties dynamicRedisProperties = multiRedisProperties.getDynamic().get(serviceName);
		if(ObjectUtil.isNull(dynamicRedisProperties) ||
				dynamicRedisProperties.isPublicPrefix()) {
			return StrUtil.EMPTY;
		}
		return serviceName;
	}

}
